$(document).ready(function () {
    loadCombo();
    loadQuickSearch();
    loadEventWithOutFocus();
    loadNavigation();
    loadCommand();
    $('a.no-follow').click(function () {
        return false;
    });
    $('ul.root li').click(function () {
        $(this).addClass('active');
    });
});

function loadNavigation() {
    $('ul.navigation li a').off('click').on('click', function (e) {
        $('ul.navigation li').removeClass('active');
        $(this).parent().addClass('active');
        var url = $(this).attr('href');
        loadAjaxContent(url);
    });
}
function loadCommand() {
    $('ul.root li a').off('click').on('click', function (e) {
        var url = $(this).attr('href');
        var data = { ids: [] };
        $('ul.list input:checked').each(function () {
            data.ids.push($(this).val());
        });
        loadAjaxCommand(url, data.ids, $(this).attr('id'));
    });
}
function ajaxLoading() {

}

function loadCommandStatus() {
    var element = $('ul.root li.active');
    element.addClass('disable');
    element.removeClass('active');
    return false;
}

function showList() {
    $('.listview').removeClass('disable');
    $('.listview').addClass('visible');
}
function loadListView() {
    loadListContent();
}

function loadContent() {
    loadQuickSearch();
    loadAdvanceSearch();
    loadFilterCategory();
    loadListView();
    //loadButton();
    $('div#msgList .listview').last().addClass('visible');
    return false;
}

function ClickActiveNavigation() {
    $('ul.root li.second').addClass('disable');
    $('ul.navigation li.active a').click();
}
function generalUrl(url) {
    $('ul.root li a').each(function () {
        var id = $(this).attr('ext');
        $(this).attr('href', url + '/' + id);
    });
}

function loadButton() {
    $('ul.root li.second').addClass('disable');
    if ($('#perJson') != null) {
        var perJson = jQuery.parseJSON($('#perJson').val());
        $(perJson).each(function (index, value) {
            if (value.ShowDefault == true) {
                var li = $('ul.root li#per' + value.Id);
                li.removeClass('disable');
                li.removeClass('second');
            }
        });
    }
    $('#as_cancel').click(function () {
        ClickActiveNavigation();
    });
}
function loadEventWithOutFocus() {
    $('.wrapper').click(function () {
        $('#headerBar').css('top', -206);
    });
    $('.msgListMainContainer').click(function () {
        $('ul.advanceSearch').slideUp(150);
    });
}

function loadQuickSearch() {
    $('.text_search').focus(function () {
        $('ul.advanceSearch').slideDown(150);
    });
}
function loadAdvanceSearch() {
    $('#as_search').click(function () {
        $('#currentPage').val(1);
        $('#totalPage').val(0);
        $('#frmSearch').submit();
    });
    $('.advanceSearch a').click(function () {
        $('div.advSearch').show();
        var msgContentHeight = $('.advSearch').innerHeight();
        $('.msgListMainContainer').css('top', msgContentHeight);
        $('ul.advanceSearch').hide();
    });
    $('#as_close').click(function () {
        $('.advSearch').hide();
        $('.msgListMainContainer').css('top', 0);
        return false;
    });
    $('ul#ulSort li').click(function () {
        $('#sort').val($(this).attr('sort'));
        $('#order').val($(this).attr('order'));
        $('#ulSort').slideUp(150);
        $('#frmSearch').submit();
    });
}
function loadCombo() {
    $('#logo_combo').click(function () {
        $('#headerBar').css('top', 0);
    });
}
function loadFilterCategory() {
    $('.sort a').click(function () {
        $(this).parent().find('ul.category').slideToggle(150);
    });
    loadChecboxAll();
}
function loadChecboxAll() {
    $('.sortItemCheckbox input[type=checkbox]').on('click', (function () {
        if ($(this).is(':checked')) {
            $('.listItems .cb input').prop('checked', true);
            $('.listItems .cb input').parents('li').addClass('selected');
        } else {
            $('.listItems .cb input').prop('checked', false);
            $('.listItems .cb input').parents('li').removeClass('selected');
        }
        loadItemSelected();
    }));
    $('#clearSelected').click(function () {
        $('.listItems .cb input').prop('checked', false);
        $('.sortItemCheckbox input[type=checkbox]').prop('checked', false);
        $('.listItems .cb input').parents('li').removeClass('selected');
        $('a.fil').show();
        $('#selectedBox').hide();
    });
}
function removePaging() {
    $('#currentPage').remove();
    $('#totalPage').remove();
}
function loadListContent() {
    $('div#msgList .listview').last().find('.page ul li a').on('click', function () {
        var idx = $(this).attr('idx'), flag = false;
        $('#currentPage').val(idx);
        $('div.listview').each(function () {
            if ($(this).attr('idx') == idx) {
                flag = true;
                $('div#msgList .listview').addClass('disable');
                $('div#msgList .listview').removeClass('visible');
                $(this).removeClass('disable');
                $(this).addClass('visible');
                return;
            }
        });
        if (!flag) {
            $('#frmSearch').submit();
            $('div#msgList .listview').last().addClass('visible');
        }
    });
    $('.listItems .cb input').on('click', (function () {
        if ($(this).is(':checked')) {
            $(this).parents('li').addClass('selected');
        } else {
            $(this).parents('li').removeClass('selected');
        }
        loadItemSelected();
    }));
    $('div#msgList .listview').addClass('disable');
    $('div#msgList .listview').last().removeClass('disable');
}
function loadItemSelected() {
    var liTotal = $('div#msgList .visible').find('.listItems ul.list li').size();
    var liChecked = $('div#msgList .visible').find('.listItems ul.list li span.cb input:checked').size();
    if (liChecked > 0) {
        $('#selectedBox').show();
        $('#itemSelected').html(liChecked + ' bản ghi đã được chọn');
        $('a.fil').hide();
        //$('ul.root li').removeClass('disable');
        loadButtomPermission();
        if (liChecked > 1) {
            $('ul.root li.single').addClass('disable');
        }
    } else {
        $('a.fil').show();
        $('#selectedBox').hide();
        $('ul.root li.second').addClass('disable');
    }
    if (liTotal == liChecked) {
        $('.sortItemCheckbox input').prop('checked', 'checked');
    } else {
        $('.sortItemCheckbox input').prop('checked', false);
    }
}

function loadButtomPermission() {
    if ($('#perJson') != null) {
        var perJson = jQuery.parseJSON($('#perJson').val());
        $(perJson).each(function (index, value) {
            var li = $('ul.root li#per' + value.Id);
            li.removeClass('disable');
        });
    }
}
function loadAjaxCommand(url, ids, action) {
    try {
        if (action == 'delete') {
            if (!confirm('Xóa bản ghi ?')) {
                return false;
            }
        }
        $.ajax({
            url: url,
            type: 'GET',
            data: { 'idJson': JSON.stringify(ids, null, 2) },
            datatype: 'json',
            beforeSend: function (xhr) { },
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (action == 'delete') {
                    if (data.message == null) {
                        ClickActiveNavigation();
                    }
                } else {
                    $('#content-main').html(data);
                }
                loadContent();
                saveDataAjaxSubmit();
            },
            error: function (request, status, error) {
                alert(error);
            }
        });
    } catch (e) { }
    return false;
}
function loadAjaxContent(url) {
    try {
        $.ajax({
            url: url,
            type: 'GET',
            datatype: 'json',
            beforeSend: function (xhr) { },
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $('#content-main').html(data);
                loadContent();
                loadButton();
                saveDataAjaxSubmit();
            },
            error: function (request, status, error) {
                alert(error);
            }
        });
    } catch (e) { }
    return false;
}

var initMessages = {};
function saveDataAjaxSubmit() {
    var options = {
        type: 'POST',
        beforeSubmit: showRequest,  // pre-submit callback         
        success: showResponse,  // post-submit callback 
        error: function () {
            alert('Error');
        },
        dataType: 'json',
    };
    try {
        jQuery("#commitData").validate({
            messages: initMessages,
            submitHandler: function (form) {
                if ($('form').serialize() != $('form').data('initialData')) {
                    jQuery(form).ajaxSubmit(options);
                }
            }
        });
        jQuery("#frmSearch").validate({
            messages: initMessages,
            submitHandler: function (form) {
                if ($('form').serialize() != $('form').data('initialData')) {
                    jQuery(form).ajaxSubmit({
                        type: 'POST',
                        target: '#msgList',
                        success: function () {
                            showList();
                            loadListContent();
                        }
                    });
                }
            }
        });
    } catch (e) { }

}
function showRequest(formData, jqForm, options) {
    return true;
}
function showResponse(responseText, statusText, xhr, $form) {
    if (responseText == null) {
        responseText = { 'message': null };
    }
    if (responseText != null && !isNaN(responseText.message)) {
        ClickActiveNavigation();
    } else {
        alert(responseText.message);
    }
}
$(function () {
    $('form').each(function () {
        $(this).data('initialData', $(this).serialize());
    }).submit(function (e) {
        e.preventDefault();
        //if ($(this).serialize() != $(this).data('initialData')) {
        //    alert('Form data has changed');
        //} else {
        //    alert('Form data is the same');
        //}
    });
});

function assignToSite() {
    var data = { ids: [] };
    $('ul.list input:checked').each(function () {
        data.ids.push({ 'SiteId': $(this).val(), 'PermissionId': $('#perId').val() });
    });
    $('#tableJson').val(JSON.stringify(data.ids, null, 2));
}

function assignToRole() {
    var data = { ids: [] };
    $('ul.list input:checked').each(function () {
        var siteId = $(this).parents('li').attr('id');
        data.ids.push({ 'SiteId': siteId, 'PermissionId': $(this).val(), 'RoleId': $('#roleId').val() });
    });
    $('#tableJson').val(JSON.stringify(data.ids, null, 2));
}